package cn.changeforyou.demo.netty.common;

import cn.changeforyou.demo.netty.common.Data.MsgType;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ReplayingDecoder;
import io.netty.util.CharsetUtil;
import java.util.LinkedHashMap;
import java.util.List;

/**
 * @author zhyu
 * @date 2021/3/15 17:10
 */
public class YbkjTcpDataDecoder extends ReplayingDecoder {

    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
        String head = in.readBytes(10).toString(CharsetUtil.UTF_8);
        String projectName = in.readBytes(7).toString(CharsetUtil.UTF_8);
        MsgType msgType = MsgType.valueOf(in.readByte());
        short contentLength = in.readShort();
        String contentStr = in.readBytes(contentLength).toString(CharsetUtil.UTF_8);
        long time = in.readLong();
        Object content;
        String foot = in.readBytes(14).toString(CharsetUtil.UTF_8);
        if (msgType == MsgType.json) {
            content = JsonUtils.toEntity(contentStr, LinkedHashMap.class);
        } else if (msgType == MsgType.heart) {
            content = contentStr;
        } else if( msgType == MsgType.req){
            content = JsonUtils.toEntity(contentStr, Req.class);
        }else if(msgType == MsgType.response){
            content = JsonUtils.toEntity(contentStr, Res.class);
        }else {
            content = contentStr;
        }
        Data data = new Data(head, projectName, msgType, contentLength, content, time, foot);
        out.add(data);
    }
}
